export class BaseSocket {
    static PING_INTERVAL_TIME = 5000;
    onMessage: Function = null as any;
    onOpen: Function = null as any;
    socket: WebSocket = null as any;
    url: string;
    currentAttempt = 0;
    maxAttempts = 5;
    cur = 0;
    pause = false;

    constructor(url: string) {
        this.url = url;
    }

    init() {
        this.socket = new WebSocket(this.url);
        this.socket.onopen = ev => {
            console.log("socket onopen", ev);
            this.currentAttempt = 0;
            this.onOpen();
        };

        this.socket.onclose = ev => {
            console.log("socket onclose", ev);
            if (this.currentAttempt < this.maxAttempts) {
                setTimeout(() => this.init(), 5000); // 5秒后尝试重新连接
            } else {
                // alert('连接失败');
                console.log("Max connection attempts reached. Connection failed.");
                // Bus.emit(CONN_STATUS, 3);
            }
        };

        this.socket.onerror = ev => {
            console.log("socket onerror", ev);
            this.socket.close();
        };

        this.socket.onmessage = ev => {
            if (ev.data == "pong") {
                this.sendPing();
                return;
            }
            if (this.pause) return;

            var data = ev.data;
            var jsondata = JSON.parse(data);
            this.onMessage(jsondata);
            // const broadcast = this.map.get(jsondata.topic);
            // if (broadcast) {
            //     broadcast.handle(jsondata);
            // }
        };
    }

    togglePause() {
        this.pause = !this.pause;
        if (this.pause) {
            this.socket.close();
            this.currentAttempt = this.maxAttempts;
        } else {
            this.init();
            this.currentAttempt = 0;
        }
    }

    sendPing() {
        // Bus.emit(PING, Date.now() - this.cur);
        this.cur = Date.now();
        if (this.socket.readyState == 1) {
            this.socket.send("ping");
        } else {
            console.log("socket 已经关闭");
            // Bus.emit(PING, PING_INTERVAL_TIME);
            // Bus.emit(CONN_STATUS, 3);
        }
    }
}
